package cn.kgc.bookservice.service;

import cn.kgc.bookservice.mapper.BookMapper;
import cn.kgc.librarycommon.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService{

    @Autowired
    private BookMapper bookMapper;

    @Override
    public PageResult<BookInfo> getAllBooks(Integer pageNo, Integer pageSize, String bookName, String authorName, Integer cid) {
        PageHelper.startPage(pageNo,pageSize);
        List<BookInfo> bookList = bookMapper.getAllBooks(bookName, authorName, cid);
        PageInfo<BookInfo> info = new PageInfo<>(bookList);
        PageResult<BookInfo> pageResult = new PageResult<>();
        pageResult.setCurrentPage(pageNo);
        pageResult.setPageSize(pageSize);
        pageResult.setResultList(bookList);
        pageResult.setTotalCount((int)info.getTotal());
        pageResult.setTotalPages(info.getPages());
        return pageResult;
    }

    @Override
    public List<Category> getAllCategory() {
        return bookMapper.getAllCategory();
    }

    @Override
    public Integer borrow(Integer uid, Integer fid) {
        Borrow borrow = new Borrow();
        //获取可借出图书列表的第一个
        List<Book> bookList = bookMapper.getEnableBook(fid);
        if(bookList.size() == 0){
            return -1;
        }
        Integer bid = bookList.get(0).getBid();
        borrow.setBid(bid);
        borrow.setUid(uid);
        borrow.setDate(new Date());
        return bookMapper.borrow(borrow);
    }

    @Override
    public List<BorrowVO> getBorrowById(Integer uid) {
        return bookMapper.getBorrowById(uid);
    }
}